import {
    Subject
} from 'rxjs'
export const subject = new Subject()


class GlobalState {
    constructor(state) {
        this._state = state
        this._subject = new Subject()
        this.subs = []
    }
    onGlobalStateChange = (cb, fireimmediately) => {
        if (fireimmediately) cb(this._state)
        const sub = this._subject.subscribe({
            next: v => {
                cb(v, this._state)
            }
        })
        this.subs.push(sub)
    }
    setGlobalState = (state) => {
        this._subject.next(state)
        this._state = state
    }
    offGlobalState = () => {
        this.subs.forEach(sub => {
            sub.unsubscribe()
        })
    }
}
class ChildState {
    constructor(global) {
        this._global = global
        this.subs = []
    }
    onGlobalStateChange = (cb, fireimmediately) => {
        const global =  this._global
        if (fireimmediately) cb( global._state)
        const sub = global._subject.subscribe({
            next: v => {
                cb(v, global._state)
            }
        })
        this.subs.push(sub)
    }
    setGlobalState = (state) => {
        this._global._subject.next(state)
        this._global._state = state
    }
    offGlobalState = () => {
        this.subs.forEach(sub => {
            sub.unsubscribe()
        })
    }
}
export function initGlobalState(state) {
    return new GlobalState(state)
}
export function initChildState(global){
    return new ChildState(global)
}